package com.cmwa.solution.filter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.cmwa.ec.base.util.StringUtil;

public class FHttpServletRequest extends HttpServletRequestWrapper {
	private String[] regs;
	
	private FHttpServletRequest(HttpServletRequest request) {
		super(request);
	}
	
	public FHttpServletRequest(HttpServletRequest request, String reg) {
		super(request);
		this.regs = reg.split("_");
	}

	@Override
	public String getParameter(String name) {
		return replace(super.getParameter(name));
	}
	
	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if(values == null || values.length == 0){
			return values;
		}
		for (int i = 0; i < values.length; i++) {
			values[i] = replace(values[i]);
		}
		return values;
	}
	
	@SuppressWarnings({ "rawtypes"})
	@Override
	public Map getParameterMap() {
		Map map = super.getParameterMap();
		Map<Object, Object> result = new HashMap<Object, Object>();
		for (Object obj : map.keySet()) {
			Object value = map.get(obj);
			
			if(value instanceof String){
				result.put(obj, replace(map.get(obj).toString()));
			}else if(value instanceof String[]){
				String[] values = (String[])value;
				for (int i = 0; i < values.length; i++) {
					values[i] = replace(values[i]);
				}
				result.put(obj, values);
			}else{
				result.put(obj, value);
			}
		}
		return result;
	}
	
	private String replace(String str){
		if(StringUtil.isEmpty(str)){
			return str;
		}
		for (String string : regs) {
        	str = str.replaceAll(string, "");
		}
		return str;
	}
}
